import { Component, OnInit, ViewChild } from '@angular/core';
import { STComponent, STColumn, STChange, STData } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { SettingsService } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SystemService } from '../../services/system.service';
import { SystemStaffStaffModalComponent } from './staff-modal/staff-modal.component';
import { BuyerTranspowerComponent } from './transpower/transpower.component';

@Component({
  selector: 'app-staff-management',
  templateUrl: './staff-management.component.html',
  styleUrls: ['./staff-management.component.less']
})
export class StaffManagementComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;

  searchSchema: SFSchema = {
    properties: {
      nameOrPhone: {
        type: 'string',
        title: '输入搜索',
        ui: { placeholder: '手机号码 / 成员姓名' }
      }
    }
  };

  columns: STColumn[] = [
    { title: '', index: 'key', className: 'text-center', type: 'checkbox' },
    {
      title: '序号',
      className: 'text-center',
      width: '60px',
      format: (item: STData, col: STColumn, idx: number) => {
        return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
      } 
    },
    { title: '员工姓名', className: 'text-center', index: 'name' },
    { title: '手机号码', className: 'text-center', index: 'telephone' },
    { title: '角色', className: 'text-center', index: 'roleName' },
    {
      title: '最后登录时间',
      index: 'lastLoginDate',
      className: 'text-center',
      type: 'date',
      format: item => `${item.lastLoginDate || '-'}`
    },
    {
      title: '成员状态',
      className: 'text-center',
      index: 'stateLocked',
      type: 'badge',
      badge: {
        0: { text: '正常', color: 'success' },
        1: { text: '冻结', color: 'error' }
      }
    },
    {
      title: '操作',
      className: 'text-center',
      buttons: [
        {
          text: '编辑',
          click: item => this.staffAction(item),
          acl: { ability: ['SYSTEM-STAFF-edit'] }
        },
        {
          text: '恢复',
          iif: item => item.stateLocked === 1 && item.telephone !== this.user.phone,
          click: item => this.action(item, 2),
          acl: { ability: ['SYSTEM-STAFF-lock'] }
        },
        {
          text: '冻结',
          iif: item =>
            !item.stateLocked && item.roleCode.split(',').indexOf('Administrator') === -1 && item.telephone !== this.user.phone,
          click: item => this.action(item, 1),
          acl: { ability: ['SYSTEM-STAFF-lock'] }
        },
        {
          text: '超管转授',
          iif: item => !item.stateLocked && item.roleCode.split(',').indexOf('Administrator') === -1,
          click: item => this.transpowerAction(item),
          acl: { ability: ['SYSTEM-STAFF-shiftAdmin'] }
        },
        {
          text: '删除',
          iif: item =>
            !item.stateLocked && item.roleCode.split(',').indexOf('Administrator') === -1 && item.telephone !== this.user.phone,
          click: item => this.action(item, 3),
          acl: { ability: ['SYSTEM-STAFF-delete'] }
        }
      ]
    }
  ];

  selectedRows: any[] = [];

  actionLabel = {
    1: { title: '确认冻结？', text: '冻结后用户在本系统将无法登录使用，请谨慎操作！' },
    2: { title: '确认恢复？', text: '恢复后用户在本系统的权限将一并重新开启。' },
    3: { title: '确认删除？', text: '删除后该用户ID将在本系统中将无法登录使用并删除，请谨慎操作！' }
  };

  user = this.setting.user;
  constructor(public service: SystemService, private nzModalService: NzModalService, private setting: SettingsService) {}

  ngOnInit(): void {}

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
    }
  }

  action(item: any, type: 1 | 2 | 3) {
    this.nzModalService.error({
      nzTitle: this.actionLabel[type].title,
      nzContent: `<label class="error-color">${this.actionLabel[type].text}</label>`,
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {
        switch (type) {
          case 1:
            this.freeOrResumStaff({ appUserId: [item.appUserId], freezeOrResume: true });
            break;
          case 2:
            this.freeOrResumStaff({ appUserId: [item.appUserId], freezeOrResume: false });
            break;
          case 3:
            this.deleteStaff([item.appUserId]);
            break;

          default:
            break;
        }
      }
    });
  }

  transpowerAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '超级管理员转授',
      nzContent: BuyerTranspowerComponent,
      nzComponentParams: { i: { ...item } },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  staffAction(item?: any) {
    const modal = this.nzModalService.create({
      nzContent: SystemStaffStaffModalComponent,
      nzComponentParams: item ? { i: { ...item, roleId: item.roleId ? (item.roleId as string)?.split(',') : null } } : { i: { userId: 0 } },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
  }

  exportList() {
    const params = { nameOrPhone: this.sf?.value?.nameOrPhone };
    this.service.downloadFile(this.service.$api_export_staff, { ...params, pageSize: -1 });
  }

  private deleteStaff(params: any) {
    this.service.request(this.service.$api_delete_staff, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('操作成功');
        this.st.load();
      }
    });
  }

  private freeOrResumStaff(params: any) {
    this.service.request(this.service.$api_free_or_resume_staff, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('操作成功');
        this.st.load();
      }
    });
  }
}
